import { PlusOutlined } from '@ant-design/icons';
import { message, Modal, Upload, UploadFile, UploadProps } from 'antd';
import React, { useState } from 'react';
import { history, useDispatch } from 'umi';
import configs from '../../../config/env';
interface PicUploadProps {
  multiple: boolean;
  maxCount: number;
  onsuccess: (fileName: string) => void;
}
const PicUpload: React.FC<PicUploadProps> = (props) => {
  const { multiple, maxCount, onsuccess } = props;
  const headers = {
    Authorization: localStorage.getItem('token') as string,
  };
  const dispatch = useDispatch();
  const uploadImgUrl = `${configs[process.env.API_ENV as any].API_SERVER}/common/upload`; // 上传的图片服务器地址
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewTitle, setPreviewTitle] = useState('');
  const [previewImage, setPreviewImage] = useState('');
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [fileTypeVaild, setfileTypeVaild] = useState<boolean>(false);
  const handleCancel = () => setPreviewOpen(false);
  const handlePreview = async (file: UploadFile) => {
    const {
      response: { newFileName, url },
    } = file;
    setPreviewImage(url);
    setPreviewOpen(true);
    setPreviewTitle(newFileName);
  };

  const handleChange: UploadProps['onChange'] = async ({ fileList: newFileList }) => {
    let arr: string[] = [];
    if (fileTypeVaild) {
      setFileList(newFileList);
      newFileList.forEach((item) => {
        if (item.response?.code !== 200 && item.status === 'done') {
          if (item.response?.code === 401) {
            setFileList(newFileList.filter((item) => item.response.code !== 401));
            localStorage.removeItem('token');
            dispatch({ type: 'userInfoModel/updateLoginState', isLogin: false });
            message.error('登录超时或者未登陆，请登录');
            history.replace('/login');
            return;
          }
          return message.error(item.response?.msg);
        }
        if (item.status === 'done') {
          arr.push(item.response.fileName);
          onsuccess(arr.toString());
        }
      });
    }
    // if (file.status === 'uploading') {
    //   return;
    // }
    // if (file.status === 'done') {
    //   console.log('img upload succeed');
    // }
  };
  const beforeUpload = (file: File) => {
    const isFileTypeValid =
      file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg';
    if (!isFileTypeValid) {
      message.error('只能上传 JPG/PNG/JPEG 格式的文件!');
    }
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
      message.error('图片必须小于 5MB!');
    }
    setfileTypeVaild(isFileTypeValid && isLt5M);
    return isFileTypeValid && isLt5M;
  };
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  );
  return (
    <>
      <Upload
        action={uploadImgUrl}
        listType="picture-card"
        fileList={fileList}
        onPreview={handlePreview}
        onChange={handleChange}
        multiple={multiple}
        maxCount={maxCount}
        beforeUpload={beforeUpload}
        headers={headers}
      >
        {fileList.length >= maxCount ? null : uploadButton}
      </Upload>

      <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
        <img alt="example" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </>
  );
};
export default PicUpload;
